package com.yinxing.webapi.code.service.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yinxing.framework.mybatis.TemplateService;
import com.yinxing.webapi.code.entity.sys.SysRolemenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ISysRolemenuService extends TemplateService<SysRolemenu> {

    /**
     * 查询菜单ID集合
     * @param sysRoleId 角色ID
     */
    public Set<Long> selectMenuIdsByRoleId(long sysRoleId) {
        LambdaQueryWrapper<SysRolemenu> qw = new LambdaQueryWrapper<>();
        //根据角色ID构造查询条件(SysRoleId_ = ?)
        qw.eq(SysRolemenu::getSysRoleId_, sysRoleId);
        List<SysRolemenu> list = selectList(qw);

        //提取实体类的SysMenu.Id_转为Set
        Set<Long> menuIds = list.stream().map(sysRolemenu ->
                sysRolemenu.getSysMenuId_()).collect(Collectors.toSet());
        return menuIds;
    }

    /**
     * 解绑角色和菜单
     * @param sysRoleId 角色ID
     * @param sysMenuId 菜单ID
     */
    public void unbindRoleMenu(long sysRoleId, long sysMenuId) {
        LambdaQueryWrapper<SysRolemenu> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRolemenu::getSysRoleId_, sysRoleId);
        qw.eq(SysRolemenu::getSysMenuId_, sysMenuId);
        super.delete(qw);
    }

    /**
     * 绑定角色和菜单
     * @param sysRoleId 角色ID
     * @param sysMenuId 菜单ID
     */
    public void bindRoleMenu(long sysRoleId, long sysMenuId) {
        if(selectRoleMenu(sysRoleId, sysMenuId) == null) {
            SysRolemenu rolemenu = new SysRolemenu();
            rolemenu.setSysRoleId_(sysRoleId);
            rolemenu.setSysMenuId_(sysMenuId);
            super.insert(rolemenu);
        }
    }

    /**
     * 查询角色菜单绑定数据
     * @param sysRoleId 角色ID
     * @param sysMenuId 菜单ID
     */
    public SysRolemenu selectRoleMenu(long sysRoleId, long sysMenuId) {
        LambdaQueryWrapper<SysRolemenu> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRolemenu::getSysRoleId_, sysRoleId);
        qw.eq(SysRolemenu::getSysMenuId_, sysMenuId);
        return selectOne(qw);
    }

    /**
     * 根据菜单ID删除全部数据
     * @param sysMenuId 菜单ID
     */
    public void deleteByMenuId(long sysMenuId) {
        LambdaQueryWrapper<SysRolemenu> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRolemenu::getSysMenuId_, sysMenuId);
        super.delete(qw);
    }

    /**
     * 根据角色ID删除全部数据
     * @param sysRoleId 角色ID
     */
    public void deleteByRoleId(long sysRoleId) {
        LambdaQueryWrapper<SysRolemenu> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRolemenu::getSysRoleId_, sysRoleId);
        super.delete(qw);
    }
}